package com.study.mybatis.demo.dao;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.study.mybatis.demo.model.UserInfo;

public class MybatisTest {
	
	private SqlSessionFactory sqlSessionFactory;
	
	@Before
	public void init() throws IOException{
		String resource = "mybatis-config.xml";
		InputStream inputStream = Resources.getResourceAsStream(resource);
		sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
	}
	
	@Test
	public void testTransaction(){
		SqlSession sqlSession = null;
		try{
			sqlSession = sqlSessionFactory.openSession(false);//ture为自动提交事务， false为手动提交即：sqlSession.commit();
			int result = sqlSession.delete("demo.classes.deleteById",3);
			System.out.println(result);
			result = sqlSession.delete("demo.student.deleteByClassesId",3);
			System.out.println(result);
			int i = 1/0;
			sqlSession.commit();
		}catch(Exception e){
			sqlSession.rollback();
			e.printStackTrace();
		}finally {
			sqlSession.close();
		}
	}
	
	
	
	@Test
	public void testAnnotation(){
		SqlSession sqlSession = null;
		try{
			sqlSession = sqlSessionFactory.openSession(true);//ture为自动提交事务， false为手动提交即：sqlSession.commit();
			UserMapper userDao = sqlSession.getMapper(UserMapper.class);
			UserInfo userInfo = new UserInfo(0,"Jack.Cheng","123456","first user");
			
			userDao.insert(userInfo);
			
			UserInfo newInfo = userDao.getUser(1);
			System.out.println(newInfo);
			System.out.println(userDao.getAllUsers());
			userDao.delete(1);
			
		}catch(Exception e){
			e.printStackTrace();
		}finally {
			sqlSession.close();
		}
	}
	
	@After
	public void close(){
//		sqlSessionFactory.
	}

}
